package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 营业额统计
     *
     * @param begin
     * @param end
     * @return
     */
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();
        //计算要计算的所有日期,加入集合
        List<LocalDate> list = new ArrayList<>();
        list.add(begin);
        LocalDate localDate = begin;
        while (!localDate.equals(end)) {
            localDate = localDate.plusDays(1);
            list.add(localDate);
        }
        //将日期拼接成字符串
        list.add(end);
        String dateList = StringUtils.join(list, ",");
        log.info("统计营业额,遍历查询日期:{}", dateList);
        //查询每天的营业额
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : list) {
            //获取这一天最早时刻和最晚时刻
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //查询这一天已完成的订单金额
            Map map = new HashMap();
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);


        }
        log.info("遍历查询结果{}", turnoverList);
        //封装对象并返回
        turnoverReportVO.setDateList(dateList);
        turnoverReportVO.setTurnoverList(StringUtils.join(turnoverList, ","));
        return turnoverReportVO;
    }

    /**
     * 导出营业数据
     *
     * @param response
     */
    public void export(HttpServletResponse response) {
        //查询数据 	营业额   订单完成率	新增用户数   有效订单		平均客单价
        //查最近30天的数据
        LocalDate beginDate = LocalDate.now().minusDays(30);
        LocalDate endDate = LocalDate.now().minusDays(1);
        LocalDateTime begin = LocalDateTime.of(beginDate, LocalTime.MIN);
        LocalDateTime end = LocalDateTime.of(endDate, LocalTime.MAX);
        //查询数据
        BusinessDataVO businessData = workspaceService.getBusinessData(begin, end);
        //获取类路径下获取文件输入流
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template\\运营数据报表模板.xlsx");
        try {

            //写入数据 通过POI写入文件
            XSSFWorkbook excel = new XSSFWorkbook(in);
            XSSFSheet sheet1 = excel.getSheetAt(0);
            sheet1.getRow(1).getCell(1).setCellValue("时间:" + beginDate + "至" + endDate);
            XSSFRow row = sheet1.getRow(3);
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());

            XSSFRow row1 = sheet1.getRow(4);
            row1.getCell(2).setCellValue(businessData.getValidOrderCount());
            row1.getCell(4).setCellValue(businessData.getUnitPrice());

            //获取每天的营业数据
            for (int i = 0; i < 30; i++) {
                /*查询每一天的数据*/
                LocalDate beginDate1 = beginDate.plusDays(i);
                BusinessDataVO businessData1 = workspaceService.getBusinessData(LocalDateTime.of(beginDate1, LocalTime.MIN), LocalDateTime.of(beginDate1, LocalTime.MAX));
                row= sheet1.getRow(7+i);
                row.getCell(1).setCellValue(beginDate1.toString());//日期
                row.getCell(2).setCellValue(businessData1.getTurnover());//营业额"
                row.getCell(3).setCellValue(businessData1.getValidOrderCount());//"	有效订单"
                row.getCell(4).setCellValue(businessData1.getOrderCompletionRate());//订单完成率
                row.getCell(5).setCellValue(businessData1.getUnitPrice());//平均客单价
                row.getCell(6).setCellValue(businessData1.getNewUsers());//新增用户数
            }
            //下载数据
            //通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);
            //关流
            excel.close();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 销量排名
     *
     * @param begin
     * @param end
     * @return
     */
    public SalesTop10ReportVO getTop(LocalDate begin, LocalDate end) {
        List nameList = new ArrayList();
        List numberList = new ArrayList();
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        log.info("查询top10,时间范围:{}{}", beginTime, endTime);
        List<GoodsSalesDTO> goodsSalesDTO = orderMapper.getTop10(beginTime, endTime, Orders.COMPLETED);
        log.info("top10:{}", goodsSalesDTO);
        for (GoodsSalesDTO salesDTO : goodsSalesDTO) {
            nameList.add(salesDTO.getName());
            numberList.add(salesDTO.getNumber());
        }


        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();
    }

    /**
     * 统计订单
     *
     * @param begin
     * @param end
     * @return
     */
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        //计算要计算的所有日期,加入集合
        List<LocalDate> list = new ArrayList<>();
        list.add(begin);
        LocalDate localDate = begin;
        while (!localDate.equals(end)) {
            localDate = localDate.plusDays(1);
            list.add(localDate);
        }
        //将日期拼接成字符串
        list.add(end);
        String dateList = StringUtils.join(list, ",");
        log.info("统计用户数,遍历查询日期:{}", dateList);


        //记录当天订单数和新增数
        List<Integer> allOrderList = new ArrayList<>();
        List<Integer> okOrderList = new ArrayList<>();
        //用于计算总订单数和总有效数
        Integer countAllOrder = 0;
        Integer countokOrder = 0;
        for (LocalDate date : list) {
            //获取这一天最早时刻和最晚时刻
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //查询这一天已完成的订单数和有效订单数
            Map map = new HashMap();
            map.put("beginTime", beginTime);
            map.put("endTime", endTime);
            //查询订单数
            Integer allOrder = orderMapper.countByMap(map);
            map.put("status", Orders.COMPLETED);
            //查询有效订单数
            Integer newOrder = orderMapper.countByMap(map);
            allOrder = allOrder == null ? 0 : allOrder;
            newOrder = newOrder == null ? 0 : newOrder;
            //计算总订单数和总有效订单数
            countAllOrder += allOrder;
            countokOrder += newOrder;
            okOrderList.add(newOrder);
            allOrderList.add(allOrder);
        }
        //计算完成率
        Double CompletionRate = 0.0;
        if (countAllOrder != 0) {
            CompletionRate = (double) countokOrder / countAllOrder;
        }


        log.info("遍历有效订单数{}", okOrderList);
        log.info("遍历总订单数{}", allOrderList);
        log.info("订单总数{}", countAllOrder);
        log.info("有效订单总数{}", countokOrder);
        log.info("订单完成率{}", CompletionRate);
        //封装对象

        return OrderReportVO.builder()
                .dateList(dateList)
                .orderCompletionRate(CompletionRate)
                .totalOrderCount(countAllOrder)
                .validOrderCount(countokOrder)
                .orderCountList(StringUtils.join(allOrderList, ","))
                .validOrderCountList(StringUtils.join(okOrderList, ","))
                .build();
    }

    /**
     * 统计用户数
     *
     * @param begin
     * @param end
     * @return
     */
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        UserReportVO userReportVO = new UserReportVO();
        //计算要计算的所有日期,加入集合
        List<LocalDate> list = new ArrayList<>();
        list.add(begin);
        LocalDate localDate = begin;
        while (!localDate.equals(end)) {
            localDate = localDate.plusDays(1);
            list.add(localDate);
        }
        //将日期拼接成字符串
        list.add(end);
        String dateList = StringUtils.join(list, ",");
        log.info("统计用户数,遍历查询日期:{}", dateList);
        //查询总用户数和新增数
        List<Integer> allUserList = new ArrayList<>();
        List<Integer> newUserList = new ArrayList<>();
        for (LocalDate date : list) {
            //获取这一天最早时刻和最晚时刻
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //查询这一天已完成的订单金额
            Map map = new HashMap();
            map.put("endTime", endTime);
            Integer allUser = userMapper.countByMap(map);
            map.put("beginTime", beginTime);
            Integer newUser = userMapper.countByMap(map);
            allUser = allUser == null ? 0 : allUser;
            newUser = newUser == null ? 0 : newUser;
            newUserList.add(newUser);
            allUserList.add(allUser);

        }
        log.info("遍历新增用户数{}", newUserList);
        log.info("遍历总用户数{}", allUserList);

        userReportVO.setDateList(dateList);
        userReportVO.setNewUserList(StringUtils.join(newUserList, ","));
        userReportVO.setTotalUserList(StringUtils.join(allUserList, ","));
        return userReportVO;
    }
}
